
<template>
  <div class="accountList">
    <div class="searchBox">
      <el-form :model="searchForm" ref="searchFormRef">
        <el-row>
          <el-form-item prop="title">
            <div class="item">
              <span v-html="'标题'" class="nameSpan"></span>
              <el-input
                size="mini"
                v-model="searchForm.title"
                placeholder="请输入标题"
              ></el-input>
            </div>
          </el-form-item>
          <el-form-item prop="status">
            <div class="item">
              <span v-html="'启用状态'" class="nameSpan"></span>
              <el-select filterable 
                clearable
                v-model="searchForm.status"
                placeholder="请选择状态"
                size="mini"
              >
                <el-option
                  v-for="item in enabledOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </div>
          </el-form-item>
          <el-form-item>
            <el-button
              @click="searchClick"
              icon="el-icon-search"
              type="primary"
              size="mini"
              >查询</el-button
            >
            <el-button icon="el-icon-refresh" size="mini" @click="resetClick"
              >重置</el-button
            >
          </el-form-item>
        </el-row>
      </el-form>
    </div>
    <div class="topBtn">
      <el-button
        size="mini"
        @click="addDialogClick"
        type="success"
        plain
        icon="el-icon-plus"
        v-has="'operation:banner:add'"
        >新增banner</el-button
      >
    </div>
    <div class="tableBox" ref="tableBoxRef">
      <el-table
      :height="605"
        v-loading="tableLoading"
        :header-cell-style="{
          background: '#F8F8F8',
          color: '#333',
          fontSize: '16px',
          fontWeight: '700',
        }"
        border
        :data="tableData"
        style="width: 100%"
      >
        <el-table-column prop="bannerUrl" align="center" label="预览">
          <template slot-scope="scope">
            <el-image
              class="imgSize"
              :src="scope.row.bannerUrl"
              fit="contain"
              :preview-src-list="[scope.row.bannerUrl]"
              ><div slot="error" class="image-slot" style="margin-top: 32px">
                暂无图片
              </div></el-image
            >
          </template>
        </el-table-column>
        <el-table-column prop="title" align="center" label="标题">
        </el-table-column>
        <el-table-column prop="order" align="center" label="排序">
        </el-table-column>
        <el-table-column prop="createTime" align="center" label="创建时间">
          <template slot-scope="scope">{{
            scope.row.createTime | formatDate
          }}</template>
        </el-table-column>
        <el-table-column prop="createName" align="center" label="创建人">
        </el-table-column>
        <el-table-column prop="status" align="center" label="启用状态">
          <template slot-scope="scope">
            <el-switch
              :disabled="permissions.indexOf('operation:banner:enable') == -1"
              @change="statusChange(scope.row)"
              :active-value="1"
              :inactive-value="0"
              v-model="scope.row.status"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              icon="el-icon-edit-outline"
              size="mini"
              type="text"
              v-has="'operation:banner:edit'"
              @click="editClick(scope.row)"
              >编辑</el-button
            >
          </template>
        </el-table-column>
      </el-table>

       <el-card class="footer" v-if="total > 0">
         <div>
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-sizes="[15, 30, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
       </el-card>
    </div>

    <!-- 新增/修改权限 -->
    <el-dialog :close-on-click-modal="false" 
      :title="title"
      :visible.sync="addEditDialogVisible"
      width="1200px"
      @open="addEditDialogOpen"
      class="addEditAccountDialog"
    >
      <div class="content">
        <el-form
          :model="addEditForm"
          :rules="addEditRules"
          ref="addEditFormRef"
        >
          <el-row>
            <el-col :span="12">
              <el-form-item prop="bannerUrl" label="banner：">
                <div class="item">
                  <el-upload
                    :before-upload="beforeUpload"
                    :on-progress="handleProgiress"
                    accept=".jpg,.jpeg,.png,.JPG,.JPEG,.gif"
                    :action="$uploadUrl + '/2'"
                    list-type="picture-card"
                    :headers="postHead"
                    :show-file-list="false"
                    :on-success="handleProductPicSuccess"
                  >
                    <img
                      v-if="addEditForm.bannerUrl"
                      :src="addEditForm.bannerUrl"
                      style="width: 398px; height: 268px; display: block"
                    />
                    <i v-else class="el-icon-plus"></i>
                  </el-upload>
                  <div style="margin-left: 70px">
                    可点击图片重新上传，可上传png, jpg, bmp等图片格式文件，限制2M内
                    <div style="color: red; margin-left: 130px">
                      建议尺寸：1920*540px
                    </div>
                  </div>

                  <el-progress
                    v-if="showJinDuTao"
                    style="
                      width: 200px;
                      margin-top: 8px;
                      position: absolute;
                      left: 0;
                      right: 0;
                      margin: auto;
                    "
                    :percentage="progressPercent"
                  />
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="title" label="标题：">
                <div class="item">
                  <el-input
                    size="mini"
                    v-model="addEditForm.title"
                    placeholder="请输入标题"
                  >
                  </el-input>
                </div>
              </el-form-item>
              <el-form-item prop="order" label="排序：">
                <div class="item">
                  <el-input
                    size="mini"
                    v-model="addEditForm.order"
                    placeholder="请输入排序"
                  >
                  </el-input>
                </div>
              </el-form-item>

              <el-form-item prop="url" label="跳转链接：">
                <div class="item">
                  <el-input
                    size="mini"
                    v-model="addEditForm.url"
                    placeholder="请输入跳转链接"
                  >
                  </el-input>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div class="btns">
        <el-button size="mini" @click="closeDialog">取 消</el-button>
        <el-button
          v-clickForbidden
          size="mini"
          type="primary"
          @click="addEditDialogSaveClick"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
export default {
  data() {
    return {
      progressPercent: 0, // 进度条默认为0
      showJinDuTao: false, //控制进度条显示隐藏
      postHead: { token: localStorage.token },
      title: "",
      searchForm: {
        title: "",
        status: "",
      },
      fileList: [],
      enabledOptions: [
        { label: "启用", value: 1 },
        { label: "禁用", value: 0 },
      ],
      tableLoading: false,
      tableHeight: 50,
      tableData: [],
      pageNum: 1,
      pageSize: 15,
      total: 0,
      addEditDialogVisible: false,
      addEditForm: {
        bannerUrl: "",
        title: "",
        url: "",
        order: "",
      },
      addEditRules: {
        bannerUrl: [
          { required: true, message: "封面不能为空", trigger: "blur" },
        ],
        title: [{ required: true, message: "标题不能为空", trigger: "blur" }],
      },
      editId: "",
    };
  },

  computed: {
    ...mapGetters(["permissions", "dictList", "visitedViews"]),
  },
  created() {
    this.getBannerList();
  },
  methods: {
    closeDialog() {
      this.addEditDialogVisible = false;
    },
    beforeUpload(file) {
      var testmsg = file.name.substring(file.name.lastIndexOf(".") + 1);
      const isLt1M = file.size / 1024 / 1024 < 2;
      if (!isLt1M) {
        this.$message.error("上传文件大小不能超过 2MB!");
        file = false;
        return file;
      }
      this.$message.warning("上传中,请稍等");
      this.showJinDuTao = true;
      this.progressPercent = 0;
    },
    handleProgiress(event, file, fileList) {
      this.progressPercent = event.percent;
    },
    /**
     * 图片上传成功的事件
     * @param {*}
     */
    handleProductPicSuccess(res, file) {
      if (res.code == "00000") {
        this.addEditForm.bannerUrl = res.result.filePath;

        this.$message.success("上传成功");
      } else {
        this.$message.error(res.message);
      }
      setTimeout(() => {
        this.showJinDuTao = false;
      }, 1000);
    },
    /**
     * 新增banner
     * @param {*}
     */
    addDialogClick() {
      this.title = "新增banner";
      this.addEditForm = {
        bannerUrl: "",
        title: "",
        url: "",
        order: "",
      };
      this.addEditDialogVisible = true;
    },
    searchClick() {
      this.pageNum = 1;
      this.getBannerList();
    },
    resetClick() {
      this.$refs.searchFormRef.resetFields();
      this.pageNum = 1;
      this.getBannerList();
    },

    /**
     * 获取用户列表
     * @param {*}
     */
    async getBannerList() {
      this.tableLoading = true;
      const res = await this.$api.bannerList({
        size: this.pageSize,
        page: this.pageNum,
        condition: {
          ...this.searchForm,
        },
      });
      this.total = res.data.result.total;
      this.tableData = res.data.result.records;
      this.tableLoading = false;
    },
    /**
     * 编辑按钮
     * @param {*} row
     */
    async editClick(row) {
      this.addEditForm = {};
      this.title = "编辑banner";
      this.addEditDialogVisible = true;
      this.editId = row.id;
      this.addEditForm = JSON.parse(JSON.stringify(row));
    },
    /**
     * 状态更新回调
     * @param {*} row
     */
    async statusChange(row) {
      try {
        const flag = row.status; // 点击之后的值
        row.status = row.status === 1 ? 0 : 1; // switch点击前的状态
        const confirmTips = flag === 1 ? "启用" : "停用";
        const confirmTextTips = flag === 1 ? "显示" : "隐藏";
        //确认框
        const confirm = await this.$confirm(`确定${confirmTips}吗？`, "提示", {
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          type: "warning",
        }).catch(() => false);
        if (!confirm) return false;
        row.status = row.status === 1 ? 0 : 1;
        if (row.status == 0) {
          const res = await this.$api.statusForbidden(row.id, row.status);
          if (res.data.code == "00000") {
            this.$message.success("操作成功，此banner将不在PC端显示");
          }
        } else {
          const res = await this.$api.statusForbidden(row.id, row.status);
          if (res.data.code == "00000") {
            this.$message.success("操作成功，此banner已在PC端显示");
          }
        }

        this.getBannerList();
      } catch (error) {
        this.$message.error(error);
      }
    },

    /**
     * 切换页面大小
     * @param {*} val
     */
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageSize = val;
      this.getBannerList();
    },

    /**
     * 页码切换
     * @param {*} val
     */
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.pageNum = val;
      this.getBannerList();
    },

    /**
     * 打开新增和修改的回调
     * @param {*}
     */
    addEditDialogOpen() {
      this.progressPercent = 0;
      this.showJinDuTao = false;
      if (this.$refs.addEditFormRef) this.$refs.addEditFormRef.resetFields();
      console.log(this.addEditForm);
    },

    /**
     * 编辑保存按钮
     * @param {*}
     */
    addEditDialogSaveClick() {
      this.$refs.addEditFormRef.validate(async (boolean) => {
        if (boolean) {
          let data = {
            id: this.editId,
            ...this.addEditForm,
          };
          if (this.title == "新增banner") {
            data.id = "";
            await this.$api.addBanner(data).then((res) => {
              if (res.data.code == "00000") {
                this.$message.success("新增成功");
                this.getBannerList();
                this.addEditDialogVisible = false;
              }
            });
          } else {
            await this.$api.editBanner(data).then((res) => {
              if (res.data.code == "00000") {
                this.$message.success("修改成功");
                this.getBannerList();
                this.addEditDialogVisible = false;
              }
            });
          }
        }
      });
    },
  },
};
</script>

<style lang="less" scoped>
.accountList {
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 20px;
  .searchBox {
    .el-row {
      display: flex;
      flex-wrap: wrap;
      .el-form-item {
        margin-bottom: 0;
      }
      .item {
        display: flex;
        align-items: center;
        margin-right: 20px;
        position: relative;
        .nameSpan {
          padding-right: 10px;
          box-sizing: border-box;
          white-space: nowrap;
        }
        .el-input {
          width: 162px;
        }
      }
    }
  }
  .topBtn {
    margin: 10px 0;
    text-align: right;
  }
  .addEditAccountDialog {
    .el-form-item {
      .el-select {
        width: 100%;
      }
    }
    .btns {
      text-align: right;
      margin-bottom: 0;
    }
  }
}
/deep/.el-button--success.is-plain {
  color: #fff;
  border-color: #409eff;
  background-color: #409eff;
}
/deep/.el-form-item {
  margin-bottom: 12px;
}
.content {
  height: 42vh;
  overflow-x: hidden;
}
/deep/.el-upload--picture-card {
  width: 400px;
  height: 270px;
}
/deep/.el-upload--picture-card i {
  margin-top: 128px;
}
.imgSize {
  height: 80px;
}
</style>